<script>
import { Plus } from '@element-plus/icons-vue'
import { addBanner } from '@/api/banner'
import { ElMessage } from 'element-plus';
export default {
  name: 'addbanner',
  data () {
    return {
      imageUrl: '',
      formData: {
        alt: '',
        link: '',
        img: ''
      }
    }
  },
  methods: {
    httpRequest (options) {
      // options.file 为我们选中的文件
      console.log(options.file);

      // URL.createObjectURL 根据文件生成一个 url 地址，该地址用于展示的临时地址
      // this.imageUrl = URL.createObjectURL(options.file)

      // 1. 将图片转换成 base64

      // 创建一个文件加载器(用来读取文件)
      let reader = new FileReader()
      // 加载指定文件
      reader.readAsDataURL(options.file)

      // 监听加载完成后的回调函数
      reader.onload = () => {
        // console.log('111111111111', reader.result);
        this.imageUrl = reader.result
        this.formData.img = reader.result
      }


      // 2. 将图片传递给服务器

    },
    // 添加按钮的点击事件
    addBanner () {
      // this.
      // console.log(this.formData);
      addBanner(this.formData).then(res => {
        console.log(res);
        if (res.code == '200') {
          ElMessage.success('轮播图添加成功')
          // 提交成功后进入到轮播图列表页面
          this.$router.push('/banner/bannerlist')
        }

      })
    }
  },
  components: {
    Plus
  }
}
</script>
<template>
  <div>
    <h1>添加轮播图</h1>

    <el-form-item label="请输入 alt">
      <el-input placeholder="请输入 alt" v-model="formData.alt" />
    </el-form-item>

    <el-form-item label="请输入 link">
      <el-input placeholder="请输入 link" v-model="formData.link" />
    </el-form-item>

    <el-form-item label="请选择图片">
      <el-upload class="avatar-uploader" :http-request="httpRequest">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </el-form-item>

    <el-button @click="addBanner"> 添加 </el-button>

  </div>
</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader {
  border: 1px dashed #f66;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}


.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
